"""
启动全局资源,等待输入query
当输入query进入后根据query类型执行strategy
"""
import json
from data_resource.global_resource import GlobalResource
from data_resource.request_content import RequestContent
from data_resource.response_content import ResponseContent
from strategy.strategy_manager import StrategyManager

class Main:
    global_resource = None
    strategy_manager = None
    channel_map = None

    @classmethod
    def init(cls):
        """
        初始化所有的global资源,以及所有的manager,将所有资源都村放入global_data中
        :return:
        """
        all_config = json.load(open("./main/search_conf.json"))

        # 初始化global_resource
        cls.global_resource = GlobalResource.instance(all_config)

        # 初始化strategy manager
        cls.strategy_manager = StrategyManager(all_config["strategy"])

        # 初始化channel 与 strategy的对应关系
        cls.channel_map = all_config["channel"]

    @classmethod
    def do_query(cls, query, channel):
        """
        准备query执行的环境,包括global_resource,request_content,response_content
        实例化strategy并调用strategy
        从response_content 中取出结果并返回
        :return:
        """
        request_content = RequestContent()
        request_content.store_value("raw_query", query)
        request_content.store_value("user_id", "methali0001")
        response_content = ResponseContent()

        # 根据基本信息创建 strategy
        strategy_name = cls.channel_map[channel]
        strategy = cls.strategy_manager.get_service(strategy_name)

        # 执行strategy
        try:
            strategy.do_search(cls.global_resource, request_content, response_content)
        except Exception as e:
            print(e)

        # 获取最终结果
        if response_content.get_value("search_success"):
            response_content.store_value("final_result", [])
            return response_content.get_value("final_result")
        else:
            return None


if __name__ == "__main__":
    pass
